# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://mer.1inkpay.com:25141/acquire/acquirePlatform/api/transfer.html'

# 联赢支付 京东 QQ 银联 H5 Loki
APP_CONF = {
    '000000590000000002': {
        'API_KEY': 'c1a7d74c0cfd4420bc238e3d7d57004f'
    },
}


# 支付类型
# wxPub	微信公众账号支付
# wxPubQR	微信扫码支付
# wxH5	微信H5支付
# alipayQR	支付宝扫码支付
# alipayH5	支付宝H5
# qpay	快捷支付
# gateway	网关支付
# jdPay	京东支付
# jdQR	京东扫码支付
# qqQR	QQ扫码支付
# qqWap	QQ H5支付
# quickpassQR	银联扫码
def _get_pay_type(service):
    if service == 'quick':
        return 'qpay'
    elif service == 'qq':
        return 'qqWap'
    elif service == 'jd':
        return 'jdPay'
    else:
        return 'qqWap'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("lianyingpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("lianyingpay sign str: %s ", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_notify_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            if 'amount' in k:
                s += '%s=%s&' % (k, '%.2f' % parameter[k])
            else:
                s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("lianyingpay notify sign str: %s ", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')
    p_dict = {
        'tradeType': 'pay.submit',
        'version': '1.7',
        'channel': _get_pay_type(service),
        'mchId': app_id,
        'body': 'charge',
        'outTradeNo': str(pay.id),
        'amount': str(pay_amount),
        'settleCycle': '0',
        'notifyUrl': '{}/pay/api/{}/lianyingpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    j = json.dumps(p_dict)
    _LOGGER.info("lianyingpay create data: %s", j)
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    response = requests.post(_GATEWAY, data=j, headers=headers, timeout=10)
    _LOGGER.info("lianyingpay create payrsp data: %s", response.text)
    d = json.loads(response.text)
    return {'charge_info': d['payCode']}


# SUCCESS
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    _LOGGER.info("lianyingpay notify data: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, key)
    pay_id = data['outTradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('lianyingpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = ''
    total_fee = float(data['amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 01：未支付
    # 02：已支付
    # 05：转入退款
    # 09：支付失败
    if trade_status == '02':
        _LOGGER.info('lianyingpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'tradeType': 'trade.query',
        'version': '1.7',
        'mchId': app_id,
        'outTradeNo': str(pay_id),
        'queryType': '1',
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    _LOGGER.info("lianyingpay query data: %s", p_dict)
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    response = requests.post(_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=10)
    _LOGGER.info("lianyingpay create payrsp data: %s", response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = str(data['status'])
        total_fee = float(data['amount'])
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '02':
            _LOGGER.info('lianyingpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('lianyingpay data error, status_code: %s', response.status_code)
